package com.example.jdbc;

import org.junit.Test;

import java.sql.*;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-08 16:37
 **/
public class JDBCDemo01 {

    @Test
    public void testjdbc01() throws ClassNotFoundException, SQLException {
        //com.mysql.jdbc.Driver
        //DriverManager.registerDriver(new Driver());
        //导入jar包
        //注册驱动,mysql5之后可以免去注册驱动的步骤,
        // 在里面存在配置文件java.sql.Driver,指定了加载的驱动

        Class.forName("com.mysql.jdbc.Driver");

        //获取连接
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://192.168.23.129:3306/db24",
                "root", "7482386379zh");

        //    执行sql,获取返回结果
        String sql = "select * from student ";
        //    获取执行者对象,普通执行者
        Statement stat = con.createStatement();

        //获取预编译执行者对象
        PreparedStatement ps = con.prepareStatement(sql);

        //事务管理
        // con.setAutoCommit(false);
        // con.rollback();
        // con.commit();

        //DML语句执行
        // stat.executeUpdate(sql);
        //DQL执行语句
        // ResultSet rs = stat.executeQuery(sql);

        //接收返回结果

        ResultSet rs = stat.executeQuery(sql);
        //iterator,迭代器,下一步
        while (rs.next()) {
            //获取结果啦啦啦
            System.out.println(rs.getInt("id") + "\t"
                    + rs.getString("name"));
        }

        //释放资源
        con.close();
        stat.close();
        rs.close();
    }

    @Test
    public void testjdbc02() throws ClassNotFoundException, SQLException {
// 通过代码获得Statement对象并执行一条创表语句：创建一张学生表(id，姓名，性别)

        Connection con = DriverManager.getConnection(
                "jdbc:mysql://192.168.23.129:3306/db24",
                "root", "7482386379zh");
        Statement stat = con.createStatement();

        stat.executeUpdate("create table stu(\n" +
                "    id int primary key auto_increment,\n" +
                "    name varchar(20),\n" +
                "    gender varchar(1)\n" +
                ")");
    }
}
